using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class Player : MonoBehaviour {

    /// <summary>
    /// Cantidad de personajes que necesitan estar vivos durante la mision, si hay menos es gameover.
    /// </summary>
    public int m_AliveNeeded = 4;
    int m_Alives = 0;
    Character m_SelectedCharacter = null;

    /// <summary>
    /// intervalo de tiempo para que el doble click haga sprint;
    /// </summary>
    const float c_SprintTiming = 0.2f;
    float timerSprint = 0.0f;
    bool m_CanSprint = false;
    static public Player instance = null;

    Character[] m_Characters = new Character[4];
    int m_Cantcharacters = 0;
    
	public Transform GetSelectedCharacterTransform(){
		return m_SelectedCharacter.transform;	
	}
    public Character GetSelectedCharacter()
    {
        return m_SelectedCharacter;
    }
	
	void Start () 
    {
        instance = this;
	}

    // Update is called once per frame
    void Update() 
    {
        CheckSprint();
	}
    /// <summary>
    /// Se fija el personaje seleccionado se puede usar, ya sea si porque no esta muerto o no hay ninguno seleccionado
    /// </summary>
    /// <returns>False en caso de no poder usarlo, True si se puede</returns>
    bool IsCharacterAvailable()
    {
        if (m_SelectedCharacter == null) return false;
        return true;
    }
    public void AddCharacter(Character c,int index)
    {
        m_Characters[index] = c;
        VisionManager.GetInstance().AddCharacter(c);
        m_Cantcharacters++;
        m_Alives++;
    }
	/// <summary>
	/// Se fija si se murieron todos los personajes
	/// </summary>
	public void OnCharacterDeath()
	{
        m_Alives--;
        if (m_Alives < m_AliveNeeded)
        {
            GameManager.GetInstance().LoseGame();
        }
	}
#region Commands

    /// <summary>
    /// Ordena a una unidad a moverse.
    /// </summary>
    public void MoveUnit(Vector3 position)
    {
        if (IsCharacterAvailable())
        {
            if (m_SelectedCharacter.MoveTo(position) == false)
            {
                SoundManager.Instance.PlaySound("No", true);
            }
            if (m_CanSprint == false)
            {
                m_CanSprint = true;
                m_SelectedCharacter.m_Sprinting = false;
            }
            else
            {
                m_SelectedCharacter.Sprint();
            }
        }
    }
    public void CheckSprint()
    {
        if (m_CanSprint)
        {
            timerSprint += Time.deltaTime;
            if (timerSprint >= c_SprintTiming)
            {
                m_CanSprint = false;
                timerSprint = 0;
            }
        }
    }
    public void CrouchUnit()
    {
        if (IsCharacterAvailable())
        {
            m_SelectedCharacter.Crouch();
        }
    }

    public void SelectCharacter(Character character)
    {
        if(character != null && character.IsAlive())
        //Si esta abierto el inventario lo cierro y lo abro para que se actualize.
        if (InventoryController.GetInstance().IsOpened())
        {
            InventoryController.GetInstance().ShowGUI(false);
            m_SelectedCharacter = character;
            m_SelectedCharacter.OnSelect();
            Minimap.instance.SetTarget(character.transform);
            InventoryController.GetInstance().ShowGUI(true);
        }
        else
        {
            m_SelectedCharacter = character;
            m_SelectedCharacter.OnSelect();
            Minimap.instance.SetTarget(character.transform);
        }
    }
    public void SelectCharacter(int index)
    {
        if (index >= m_Cantcharacters) return;
        SelectCharacter(m_Characters[index]);
    }
    public void UnSelectCharacter(Character character)
    {
        if (m_SelectedCharacter == character)
        {
            if (InventoryController.GetInstance().IsOpened())
            {
                InventoryController.GetInstance().OpenInventory();
            }
            m_SelectedCharacter = null;
        }
    }
    /// <summary>
    /// Muestra la ventana de stats del personaje seleccionado.
    /// </summary>
    public void ShowStats()
    {
        if (IsCharacterAvailable())
        {
            AttributesController.GetInstance().ShowStats();
        }
    }
    /// <summary>
    /// Abre el inventario del personaje seleccionado
    /// </summary>
    public void OpenInventory()
    {
        if (IsCharacterAvailable())
        {
            InventoryController.GetInstance().OpenInventory();
        }
    }
    /// <summary>
    /// Ordena al personaje seleccionado a agarrar un item.
    /// </summary>
    /// <param name="raycastHitInfo"></param>
    public void PickUpItem(RaycastHit raycastHitInfo)
    {
        if (IsCharacterAvailable())
        {
            Item item = raycastHitInfo.collider.transform.parent.GetComponent<Item>();
            //item.OnRightClic(raycastHitInfo.point);
            m_SelectedCharacter.PickUpItem(item);
        }
    }
    /// <summary>
    /// Ordena al personaje seleccionado a agarrar un item.
    /// </summary>
    /// <param name="raycastHitInfo"></param>
    public void PickUpItem(Item item)
    {
        if (IsCharacterAvailable())
        {
            m_SelectedCharacter.PickUpItem(item);
        }
    }
    public void Equip(Equipable equippable)
    {
        if (IsCharacterAvailable())
        {
            m_SelectedCharacter.Equip(equippable,m_SelectedCharacter);
        }
        else
        {
            Debug.LogError("Personaje es no esta disponible cuando se trata de equipar algo");
        }
    }
    public void ReloadWeapon(string weaponId, Bullets bullets)
    {
        if (IsCharacterAvailable())
        {
            m_SelectedCharacter.ReloadWeapon(weaponId, bullets);
        }
    }
    public void UseEquipable(RaycastHit raycastHitInfo)
    {
        if (IsCharacterAvailable())
        {
            if (m_SelectedCharacter.HaveEquipped())
            {
                Enemy e = raycastHitInfo.transform.GetComponent<Enemy>();
                if (e != null) //si clickeaste un enemigo tiro un rayo del personaje al enemigo.
                {
                    m_SelectedCharacter.UseEquippable(e);
                }
                else
                {
                    m_SelectedCharacter.UseEquippable(raycastHitInfo.point);
                }
            }
        }
    }
    public void UseHotSkills(int index)
    {
        if (IsCharacterAvailable())
        {
            m_SelectedCharacter.m_CharacterData.UseHotSkill(index);
        }
    }
    public void UnEquip()
    {
        if (IsCharacterAvailable())
        {
            m_SelectedCharacter.UnEquip();
        }
    }
#endregion
}
